from django import forms
from web import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import random
from django.conf import settings
from django.contrib.auth import authenticate
        
class RegisterModelForm(forms.ModelForm):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ], widget=forms.TextInput(attrs={'placeholder': '请输入手机号'}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
    re_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(attrs={'placeholder': '请再次输入密码'}))
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'placeholder': '请输入验证码'}))

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        re_password = cleaned_data.get('re_password')

        if password and re_password and password != re_password:
            self.add_error('re_password', '两次密码输入不一致')

        return cleaned_data

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'phone']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 为用户名和邮箱添加placeholder
        self.fields['username'].widget.attrs['placeholder'] = '请输入用户名'
        self.fields['email'].widget.attrs['placeholder'] = '请输入邮箱'
        self.fields['password'].widget.attrs['placeholder'] = '请输入密码'
        self.fields['re_password'].widget.attrs['placeholder'] = '请再次输入密码'
        self.fields['phone'].widget.attrs['placeholder'] = '请输入手机号'
        self.fields['code'].widget.attrs['placeholder'] = '请输入验证码'
        # 为手机号添加提示信息
        self.fields['phone'].help_text = '请输入正确的手机号'
        # 为验证码添加提示信息
        self.fields['code'].help_text = '请输入正确的验证码'
        # 为密码添加提示信息
        self.fields['password'].help_text = '密码不能少于8位'
        # 为确认密码添加提示信息
        self.fields['re_password'].help_text = '两次密码输入不一致'
        # 为用户名添加提示信息
        self.fields['username'].help_text = '用户名不能少于5位'
        # 为邮箱添加提示信息
        self.fields['email'].help_text = '请输入正确的邮箱格式'  # 邮箱格式校验

    def save(self, commit=True):
        # 不直接保存，而是获取实例后设置密码
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', widget=forms.TextInput(attrs={'placeholder': '请输入用户名'}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'placeholder': '请输入验证码'}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)

    def clean_code(self):
        code = self.cleaned_data.get('code')
        session_code = self.request.session.get('image_code')
        if not session_code:
            raise ValidationError('验证码已过期，请重新获取')
        if code.upper() != session_code.upper():
            raise ValidationError('验证码错误')
        return code

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise ValidationError('用户名或密码错误')
            cleaned_data['user'] = user

        return cleaned_data


class SendSmsForm(forms.Form):
    mobilephone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ], widget=forms.TextInput(attrs={'placeholder': '请输入手机号'}))
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'placeholder': '请输入验证码'}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)

    def clean_mobilephone(self):
        """ 手机号校验的钩子 """
        mobilephone = self.cleaned_data['mobilephone']

        # 判断短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            raise ValidationError('短信模板错误')

        exists = models.UserInfo.objects.filter(phone=mobilephone).exists()
        if tpl == 'login':
            if not exists:
                raise ValidationError('手机号不存在')
        else:
            # 校验数据库中是否已有手机号
            if exists:
                raise ValidationError('手机号已存在')

        return mobilephone



